package config

// AppConfig 应用配置结构体
type AppConfig struct {
	App       AppSettings       `yaml:"app"`
	JWT       JWTSettings       `yaml:"jwt"`
	Database  DatabaseSettings  `yaml:"database"`
	Redis     RedisSettings     `yaml:"redis"`
	Log       LogSettings       `yaml:"log"`
	CORS      CORSSettings      `yaml:"cors"`
	Upload    UploadSettings    `yaml:"upload"`
	SMS       SMSSettings       `yaml:"sms"`
	Mail      MailSettings      `yaml:"mail"`
	Payment   PaymentSettings   `yaml:"payment"`
	WebSocket WebSocketSettings `yaml:"websocket"`
	Scheduler SchedulerSettings `yaml:"scheduler"`
	Queue     QueueSettings     `yaml:"queue"`
	Storage   StorageSettings   `yaml:"storage"`  // 存储配置
	Security  SecuritySettings  `yaml:"security"` // 安全配置
}

// AppSettings 应用设置
type AppSettings struct {
	Name             string `mapstructure:"name" yaml:"name"`
	Version          string `mapstructure:"version" yaml:"version"`
	Mode             string `mapstructure:"mode" yaml:"mode"`
	Port             int    `mapstructure:"port" yaml:"port"`
	APIPrefix        string `mapstructure:"api_prefix" yaml:"api_prefix"`
	StaticPath       string `mapstructure:"static_path" yaml:"static_path"`
	UploadPath       string `mapstructure:"upload_path" yaml:"upload_path"`
	LogPath          string `mapstructure:"log_path" yaml:"log_path"`
	LogLevel         string `mapstructure:"log_level" yaml:"log_level"`
	LogRetentionDays int    `mapstructure:"log_retention_days" yaml:"log_retention_days"` // 日志保留天数
}

// WebSocketSettings WebSocket配置
type WebSocketSettings struct {
	Enabled           bool   `yaml:"enabled"`
	Path              string `yaml:"path"`
	MaxMessageSize    int64  `yaml:"max_message_size"`
	WriteWait         int    `yaml:"write_wait"`
	PongWait          int    `yaml:"pong_wait"`
	PingPeriod        int    `yaml:"ping_period"`
	ReadBufferSize    int    `yaml:"read_buffer_size"`
	WriteBufferSize   int    `yaml:"write_buffer_size"`
	EnableCompression bool   `yaml:"enable_compression"`
}

// SchedulerSettings 调度器配置
type SchedulerSettings struct {
	Enabled     bool                       `yaml:"enabled"`
	Timezone    string                     `yaml:"timezone"`
	Tasks       []TaskConfig               `yaml:"tasks"`
	Distributed DistributedSchedulerConfig `yaml:"distributed"`
}

// DistributedSchedulerConfig 分布式调度器配置
type DistributedSchedulerConfig struct {
	Enabled          bool                    `yaml:"enabled"`
	ExchangeName     string                  `yaml:"exchange_name"`
	RoutingKeyPrefix string                  `yaml:"routing_key_prefix"`
	Publisher        bool                    `yaml:"publisher"`
	Consumer         bool                    `yaml:"consumer"`
	Tasks            []DistributedTaskConfig `yaml:"tasks"`
}

// DistributedTaskConfig 分布式任务配置
type DistributedTaskConfig struct {
	Name        string `yaml:"name"`
	Topic       string `yaml:"topic"`
	Spec        string `yaml:"spec"`
	Enabled     bool   `yaml:"enabled"`
	Description string `yaml:"description"`
}

// TaskConfig 任务配置
type TaskConfig struct {
	Name        string `yaml:"name"`
	Spec        string `yaml:"spec"`
	Enabled     bool   `yaml:"enabled"`
	Description string `yaml:"description"`
}

// QueueSettings 消息队列配置
type QueueSettings struct {
	Enabled  bool           `yaml:"enabled"`
	Provider string         `yaml:"provider"`
	RabbitMQ RabbitMQConfig `yaml:"rabbitmq"`
}

// RabbitMQConfig RabbitMQ配置
type RabbitMQConfig struct {
	Host         string `yaml:"host"`
	Port         int    `yaml:"port"`
	Username     string `yaml:"username"`
	Password     string `yaml:"password"`
	VHost        string `yaml:"vhost"`
	ExchangeName string `yaml:"exchange_name"`
	ExchangeType string `yaml:"exchange_type"`
	QueueName    string `yaml:"queue_name"`
	RoutingKey   string `yaml:"routing_key"`
	Durable      bool   `yaml:"durable"`
	AutoDelete   bool   `yaml:"auto_delete"`
	Exclusive    bool   `yaml:"exclusive"`
	NoWait       bool   `yaml:"no_wait"`
}

// JWTSettings JWT配置
type JWTSettings struct {
	Secret               string `yaml:"secret"`
	Expire               int    `yaml:"expire"`
	RefreshExpire        int    `yaml:"refresh_expire"`
	Issuer               string `yaml:"issuer"`
	BlacklistGracePeriod int    `yaml:"blacklist_grace_period"`
	BlacklistPrefix      string `yaml:"blacklist_prefix"`
	SigningMethod        string `yaml:"signing_method"`
	TokenType            string `yaml:"token_type"`
	TokenLookup          string `yaml:"token_lookup"`
}

// DatabaseSettings 数据库配置
type DatabaseSettings struct {
	Driver            string `yaml:"driver"`
	Host              string `yaml:"host"`
	Port              int    `yaml:"port"`
	Username          string `yaml:"username"`
	Password          string `yaml:"password"`
	Database          string `yaml:"database"`
	Charset           string `yaml:"charset"`
	MaxIdleConns      int    `yaml:"max_idle_conns"`
	MaxOpenConns      int    `yaml:"max_open_conns"`
	ConnMaxLifetime   int    `yaml:"conn_max_lifetime"`
	TablePrefix       string `yaml:"table_prefix"`
	LogLevel          string `yaml:"log_level"`
	SlowThreshold     int    `yaml:"slow_threshold"`
	EnableAutoMigrate bool   `yaml:"enable_auto_migrate"`
}

// RedisSettings Redis配置
type RedisSettings struct {
	Host          string   `yaml:"host"`
	Port          int      `yaml:"port"`
	Password      string   `yaml:"password"`
	DB            int      `yaml:"db"`
	PoolSize      int      `yaml:"pool_size"`
	MinIdleConns  int      `yaml:"min_idle_conns"`
	DialTimeout   int      `yaml:"dial_timeout"`
	ReadTimeout   int      `yaml:"read_timeout"`
	WriteTimeout  int      `yaml:"write_timeout"`
	EnableCluster bool     `yaml:"enable_cluster"`
	ClusterNodes  []string `yaml:"cluster_nodes"`
}

// LogSettings 日志配置
type LogSettings struct {
	Level         string `yaml:"level"`
	Format        string `yaml:"format"`
	Path          string `yaml:"path"`
	MaxSize       int    `yaml:"max_size"`
	MaxBackups    int    `yaml:"max_backups"`
	MaxAge        int    `yaml:"max_age"`
	Compress      bool   `yaml:"compress"`
	EnableConsole bool   `yaml:"enable_console"`
	EnableCaller  bool   `yaml:"enable_caller"`
	EnableColor   bool   `yaml:"enable_color"`
}

// CORSSettings 跨域配置
type CORSSettings struct {
	Enable           bool     `yaml:"enable"`
	AllowOrigins     []string `yaml:"allow_origins"`
	AllowMethods     []string `yaml:"allow_methods"`
	AllowHeaders     []string `yaml:"allow_headers"`
	ExposeHeaders    []string `yaml:"expose_headers"`
	AllowCredentials bool     `yaml:"allow_credentials"`
	MaxAge           int      `yaml:"max_age"`
}

// UploadSettings 文件上传配置
type UploadSettings struct {
	SavePath         string   `yaml:"save_path"`
	MaxSize          int      `yaml:"max_size"`
	AllowedExts      []string `yaml:"allowed_exts"`
	ImageMaxWidth    int      `yaml:"image_max_width"`
	ImageMaxHeight   int      `yaml:"image_max_height"`
	ThumbnailWidth   int      `yaml:"thumbnail_width"`
	ThumbnailHeight  int      `yaml:"thumbnail_height"`
	ThumbnailQuality int      `yaml:"thumbnail_quality"`
}

// SMSSettings 短信配置
type SMSSettings struct {
	Provider       string     `yaml:"provider"`
	Aliyun         AliyunSMS  `yaml:"aliyun"`
	Tencent        TencentSMS `yaml:"tencent"`
	CodeLength     int        `yaml:"code_length"`
	ExpireTime     int        `yaml:"expire_time"`
	CooldownTime   int        `yaml:"cooldown_time"`
	DailyLimit     int        `yaml:"daily_limit"`
	EnableTestMode bool       `yaml:"enable_test_mode"`
	TestCode       string     `yaml:"test_code"`
}

// AliyunSMS 阿里云短信配置
type AliyunSMS struct {
	AccessKeyID     string            `yaml:"access_key_id"`
	AccessKeySecret string            `yaml:"access_key_secret"`
	SignName        string            `yaml:"sign_name"`
	Templates       map[string]string `yaml:"templates"`
}

// TencentSMS 腾讯云短信配置
type TencentSMS struct {
	AppID     string            `yaml:"app_id"`
	AppKey    string            `yaml:"app_key"`
	SignName  string            `yaml:"sign_name"`
	Templates map[string]string `yaml:"templates"`
}

// MailSettings 邮件配置
type MailSettings struct {
	Enable         bool   `yaml:"enable"`
	Host           string `yaml:"host"`
	Port           int    `yaml:"port"`
	Username       string `yaml:"username"`
	Password       string `yaml:"password"`
	FromName       string `yaml:"from_name"`
	FromEmail      string `yaml:"from_email"`
	SubjectPrefix  string `yaml:"subject_prefix"`
	TemplatesPath  string `yaml:"templates_path"`
	EnableHTML     bool   `yaml:"enable_html"`
	EnableSSL      bool   `yaml:"enable_ssl"`
	EnableTestMode bool   `yaml:"enable_test_mode"`
}

// PaymentSettings 支付配置
type PaymentSettings struct {
	// 支付宝配置
	Alipay AlipaySettings `yaml:"alipay"`
}

// AlipaySettings 支付宝配置
type AlipaySettings struct {
	AppID           string `yaml:"app_id"`
	PrivateKey      string `yaml:"private_key"`
	AlipayPublicKey string `yaml:"alipay_public_key"`
	NotifyURL       string `yaml:"notify_url"`
	ReturnURL       string `yaml:"return_url"`
}

// StorageSettings 存储配置
type StorageSettings struct {
	Provider     string               `yaml:"provider"`      // 存储提供商: local, oss, cos, qiniu
	UploadDir    string               `yaml:"upload_dir"`    // 上传目录
	URLPrefix    string               `yaml:"url_prefix"`    // URL前缀
	MaxSize      int64                `yaml:"max_size"`      // 最大文件大小
	AllowedTypes []string             `yaml:"allowed_types"` // 允许的文件类型
	ImageProcess ImageProcessSettings `yaml:"image_process"` // 图片处理
	Local        LocalStorageSettings `yaml:"local"`         // 本地存储配置
	OSS          OSSStorageSettings   `yaml:"oss"`           // 阿里云OSS配置
	COS          COSStorageSettings   `yaml:"cos"`           // 腾讯云COS配置
	Qiniu        QiniuStorageSettings `yaml:"qiniu"`         // 七牛云配置
}

// ImageProcessSettings 图片处理配置
type ImageProcessSettings struct {
	Enable    bool              `yaml:"enable"`     // 是否启用
	MaxWidth  int               `yaml:"max_width"`  // 最大宽度
	MaxHeight int               `yaml:"max_height"` // 最大高度
	Quality   int               `yaml:"quality"`    // 图片质量
	Watermark WatermarkSettings `yaml:"watermark"`  // 水印配置
}

// WatermarkSettings 水印配置
type WatermarkSettings struct {
	Enable   bool   `yaml:"enable"`    // 是否启用
	Text     string `yaml:"text"`      // 水印文字
	FontSize int    `yaml:"font_size"` // 字体大小
	Color    string `yaml:"color"`     // 颜色
	Position string `yaml:"position"`  // 位置
}

// LocalStorageSettings 本地存储配置
type LocalStorageSettings struct {
	RootPath   string `yaml:"root_path"`   // 根路径
	BaseURL    string `yaml:"base_url"`    // 基础URL
	CreatePath bool   `yaml:"create_path"` // 是否自动创建路径
}

// OSSStorageSettings 阿里云OSS配置
type OSSStorageSettings struct {
	AccessKeyID     string `yaml:"access_key_id"`     // 访问密钥ID
	AccessKeySecret string `yaml:"access_key_secret"` // 访问密钥密钥
	Endpoint        string `yaml:"endpoint"`          // OSS服务的访问域名
	Bucket          string `yaml:"bucket"`            // 存储空间名称
	BaseURL         string `yaml:"base_url"`          // 自定义域名（可选）
	PathPrefix      string `yaml:"path_prefix"`       // 路径前缀（可选）
	IsPublic        bool   `yaml:"is_public"`         // 是否公开访问
}

// COSStorageSettings 腾讯云COS配置
type COSStorageSettings struct {
	SecretID   string `yaml:"secret_id"`   // 密钥ID
	SecretKey  string `yaml:"secret_key"`  // 密钥
	Region     string `yaml:"region"`      // 地域
	Bucket     string `yaml:"bucket"`      // 存储桶名称
	BaseURL    string `yaml:"base_url"`    // 自定义域名（可选）
	PathPrefix string `yaml:"path_prefix"` // 路径前缀（可选）
	IsPublic   bool   `yaml:"is_public"`   // 是否公开访问
}

// QiniuStorageSettings 七牛云配置
type QiniuStorageSettings struct {
	AccessKey  string `yaml:"access_key"`  // 访问密钥
	SecretKey  string `yaml:"secret_key"`  // 密钥
	Bucket     string `yaml:"bucket"`      // 存储空间名称
	Domain     string `yaml:"domain"`      // 域名
	PathPrefix string `yaml:"path_prefix"` // 路径前缀（可选）
	IsPublic   bool   `yaml:"is_public"`   // 是否公开访问
}

// SecuritySettings 安全配置
type SecuritySettings struct {
	CSRF           CSRFSettings           `yaml:"csrf"`            // CSRF保护配置
	XSS            XSSSettings            `yaml:"xss"`             // XSS保护配置
	RateLimit      RateLimitSettings      `yaml:"rate_limit"`      // 限流保护配置
	IPBlacklist    IPBlacklistSettings    `yaml:"ip_blacklist"`    // IP黑名单配置
	PasswordPolicy PasswordPolicySettings `yaml:"password_policy"` // 密码策略配置
}

// CSRFSettings CSRF保护配置
type CSRFSettings struct {
	Enable         bool     `yaml:"enable"`           // 是否启用CSRF保护
	ExcludeURLs    []string `yaml:"exclude_urls"`     // 排除的URL列表
	HeaderName     string   `yaml:"header_name"`      // CSRF令牌请求头名称
	CookieName     string   `yaml:"cookie_name"`      // CSRF令牌Cookie名称
	CookieDomain   string   `yaml:"cookie_domain"`    // Cookie域名
	CookiePath     string   `yaml:"cookie_path"`      // Cookie路径
	CookieMaxAge   int      `yaml:"cookie_max_age"`   // Cookie最大生命周期，单位：秒
	CookieHTTPOnly bool     `yaml:"cookie_http_only"` // 是否设置HttpOnly标志
	CookieSecure   bool     `yaml:"cookie_secure"`    // 是否设置Secure标志
}

// XSSSettings XSS保护配置
type XSSSettings struct {
	Enable      bool     `yaml:"enable"`       // 是否启用XSS保护
	ExcludeURLs []string `yaml:"exclude_urls"` // 排除的URL列表
}

// RateLimitSettings 限流保护配置
type RateLimitSettings struct {
	Enable bool `yaml:"enable"` // 是否启用限流保护
	Rate   int  `yaml:"rate"`   // 限流速率，单位：次/分钟
	Burst  int  `yaml:"burst"`  // 突发流量容量
}

// IPBlacklistSettings IP黑名单配置
type IPBlacklistSettings struct {
	Enable bool     `yaml:"enable"` // 是否启用IP黑名单
	IPs    []string `yaml:"ips"`    // IP黑名单列表
}

// PasswordPolicySettings 密码策略配置
type PasswordPolicySettings struct {
	MinLength          int  `yaml:"min_length"`           // 最小长度
	RequireUppercase   bool `yaml:"require_uppercase"`    // 是否要求大写字母
	RequireLowercase   bool `yaml:"require_lowercase"`    // 是否要求小写字母
	RequireNumber      bool `yaml:"require_number"`       // 是否要求数字
	RequireSpecialChar bool `yaml:"require_special_char"` // 是否要求特殊字符
	MaxLoginAttempts   int  `yaml:"max_login_attempts"`   // 最大登录尝试次数
	LockoutDuration    int  `yaml:"lockout_duration"`     // 锁定时长，单位：秒
}
